import logging
from common.account import db as account_db
from datetime import timedelta
from common.es_core.report_creator import (
    ReportCreator,
    get_key_mapper_list,
    add_attachment_to_report_config,
    generate_chn_filter_dsl,
    get_daily_first_recharge
)
from event_rule.dwc.marketing_event.s2s_report_v2 import S2S_REPORT_CONFIG_V2
from event_rule.dwc.marketing_event.cps_report import CPS_REPORT_CONFIG
from event_rule.dwc.marketing_event.daily_user_report_v2 import DAILY_USER_REPORT_V2
from event_rule.dwc.marketing_event.daily_device_report_v2 import DAILY_DEVICE_REPORT_V2
from event_rule.dwc.marketing_event import summary_report_v2
from event_rule.dwc.attachment.channel_tax_attachment import CHANNEL_TAX_ATTACHMENT
from common.mg_core import mg
from common.permission.handler import get_key_mapper

_LOGGER = logging.getLogger(__name__)


def get_chn_list(game_id):
    channel_list = account_db.get_distinct_channel_exists_app_id(merchant_name=game_id)
    return dict(chn_list=channel_list)


def s2s_report_handler_v2(game_id, time_range,
                          chn_list=None,
                          user_channel_ttls=None,
                          banned_user_ids=None,
                          banned_channels=None):
    s2s_idx_name = '_'.join([game_id, 's2s'])
    config = add_attachment_to_report_config(S2S_REPORT_CONFIG_V2, CHANNEL_TAX_ATTACHMENT)
    dynamic_target_users_dct = get_daily_first_recharge(game_id, time_range[0], time_range[1])
    key_mapper = get_key_mapper_list(config.get("values"))
    channel_list = account_db.get_distinct_channel_exists_app_id(merchant_name=game_id)
    if chn_list:
        channel_list = list(set(channel_list).intersection(chn_list))
    data_list = []
    ttl_map = {channel_ttl['channel']: channel_ttl['ttl'] for channel_ttl in user_channel_ttls} \
        if user_channel_ttls else {}
    banned_channel_map = {banned_channel['channel']: banned_channel['max_user_id'] for banned_channel in
                          banned_channels} if banned_channels else {}
    for channel in channel_list:
        custom_filter = [
            {"exists": {"field": "_s2s_appid"}},
            {'term': {'_chn.keyword': channel}},
            {'range': {"_event_time": {"gte": int(time_range[0].timestamp()),
                                       "lt": int((time_range[1] + timedelta(days=1)).timestamp())}}}
        ]
        if channel in ttl_map:
            ttl_range_term = {'range': {'_active_days': {'lte': ttl_map[channel]}}}
            custom_filter.append(ttl_range_term)
        if channel in banned_channel_map:
            banned_channel_term = {'range': {'_user_id': {'gt': banned_channel_map[channel]}}}
            custom_filter.append(banned_channel_term)
        if banned_user_ids:
            user_ids_term = {'bool': {
                'must_not': {
                    'terms': {'_user_id': banned_user_ids}
                }
            }}
            custom_filter.append(user_ids_term)

        channel_report = ReportCreator.create_report(
            start_time=time_range[0], end_time=time_range[1],
            event_rule=config, index=','.join([game_id, s2s_idx_name]), custom_filter=custom_filter,
            dynamic_argument_dct=dynamic_target_users_dct, to_group=True
        )
        channel_report_list = channel_report['list']
        for elem in channel_report_list:
            elem['_chn'] = channel
        data_list += channel_report_list
    chn_filter_dsl = generate_chn_filter_dsl(user_channel_ttls, banned_channels, banned_user_ids)
    custom_filter = [
        {"exists": {"field": "_s2s_appid"}},
        {'range': {"_event_time": {"gte": int(time_range[0].timestamp()),
                                   "lt": int((time_range[1] + timedelta(days=1)).timestamp())}}}]
    if chn_filter_dsl:
        custom_filter += chn_filter_dsl
    if chn_list:
        custom_filter += [{"terms": {"_chn.keyword": chn_list}}]
    sum_up = ReportCreator.create_report(
        start_time=time_range[0], end_time=time_range[1], event_rule=config, index=','.join([game_id, s2s_idx_name]),
        custom_filter=custom_filter, dynamic_argument_dct=dynamic_target_users_dct
    )
    return {"list": data_list, "sum_up": sum_up, "key_mapper": key_mapper}


def dwc_cps_report_handler(game_id, time_range):
    channel_report = ReportCreator.create_report(
        start_time=time_range[0], end_time=time_range[1],
        event_rule=add_attachment_to_report_config(CPS_REPORT_CONFIG, CHANNEL_TAX_ATTACHMENT),
        index=game_id, to_group=True
    )
    channel_report_list = channel_report['list']
    for elem in channel_report_list:
        # compatible old interface
        elem['chn'] = elem.pop('_chn')
    res = [{'list': channel_report_list,
            'channel_count': channel_report['total_count']}]
    return res


def dwc_daily_user_report_v2(game_id, time_range,
                             chn_list=None,
                             user_channel_ttls=None,
                             banned_channels=None,
                             banned_user_ids=None):
    config = add_attachment_to_report_config(DAILY_USER_REPORT_V2, CHANNEL_TAX_ATTACHMENT)
    dynamic_target_users_dct = get_daily_first_recharge(game_id, time_range[0], time_range[1])
    key_mapper = get_key_mapper_list(config.get("values"))
    chn_filter_dsl = generate_chn_filter_dsl(user_channel_ttls, banned_channels, banned_user_ids)
    custom_filter = [{'range': {"_event_time": {"gte": int(time_range[0].timestamp()),
                                                "lt": int((time_range[1] + timedelta(days=1)).timestamp())}}}]
    if chn_filter_dsl:
        custom_filter += chn_filter_dsl
    if chn_list:
        custom_filter += [{"terms": {"_chn.keyword": chn_list}}]
    daily_user_report = ReportCreator.create_report(
        start_time=time_range[0], end_time=time_range[1], event_rule=config, index=game_id, custom_filter=custom_filter,
        dynamic_argument_dct=dynamic_target_users_dct, to_group=True
    )
    daily_user_report['sum_up'] = ReportCreator.create_report(
        start_time=time_range[0], end_time=time_range[1], event_rule=config,
        index=game_id, custom_filter=custom_filter, custom_not_filter=[{"term": {"bet_order_user_type": 1}}],
        dynamic_argument_dct=dynamic_target_users_dct
    )
    daily_user_report.update({"key_mapper": key_mapper})
    return daily_user_report


def dwc_daily_device_report_v2(game_id, time_range,
                               chn_list=None,
                               user_channel_ttls=None,
                               banned_channels=None,
                               banned_user_ids=None):
    config = add_attachment_to_report_config(DAILY_DEVICE_REPORT_V2, CHANNEL_TAX_ATTACHMENT)
    key_mapper = get_key_mapper_list(config.get("values"))
    chn_filter_dsl = generate_chn_filter_dsl(user_channel_ttls, banned_channels, banned_user_ids)
    custom_filter = []
    if chn_filter_dsl:
        custom_filter += chn_filter_dsl
    if chn_list:
        custom_filter += [{"terms": {"_chn.keyword": chn_list}}]
    daily_device_report = ReportCreator.create_report(
        start_time=time_range[0], end_time=time_range[1], event_rule=config, index=game_id,
        custom_filter=custom_filter, to_group=True
    )
    daily_device_report['sum_up'] = ReportCreator.create_report(
        start_time=time_range[0], end_time=time_range[1], event_rule=config,
        index=game_id, custom_filter=custom_filter
    )
    daily_device_report.update({"key_mapper": key_mapper})
    return daily_device_report


def dwc_summary_report_v2(app_name, time_range):
    report = ReportCreator.create_report(start_time=time_range[0], end_time=time_range[1],
                                         event_rule=summary_report_v2.DAILY_USER_REPORT, index=app_name)
    dynamic_argument_dct = get_daily_first_recharge(app_name, time_range[0], time_range[1])
    dynamic_argument_dct.update({
        'total_tax_amount': report.get('tax_amount'),
        'total_choushui_amount': report.get('profit')
    })
    game_report = ReportCreator.create_report(start_time=time_range[0], end_time=time_range[1],
                                              event_rule=summary_report_v2.GAME_REPORT, index=app_name,
                                              dynamic_argument_dct=dynamic_argument_dct, to_group=True)
    key_mapper = get_key_mapper_list(summary_report_v2.DAILY_USER_REPORT.get("values"))
    return {"summary": report, "game": game_report, "key_mapper": key_mapper}


def get_active_user_report(game_id, time_range):
    condition = {'updated_at': {"$gte": time_range[0], "$lt": time_range[1]}}
    reports = mg.get_report(game_id, 'user_active_user_analysis_report', condition, 'day', disable_paginate=True)
    resp_items = [report for report in reports]
    key_mapper = get_key_mapper(game_id, '4002')
    if not resp_items:
        return dict(msg="数据暂未生成，请稍后再试")
    return dict(values=resp_items, key_mapper=key_mapper)
